package com.foreverwin.jzymes.framework.aspect;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.jzymes.common.domain.EapLog;
import com.foreverwin.jzymes.framework.util.IPUtil;
import com.foreverwin.jzymes.framework.util.ObjectMapperUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

@Aspect
@Component
public class MessageLogAspect {

    private Logger logger = LoggerFactory.getLogger( MessageLogAspect.class );

    @Autowired
    JmsMessagingTemplate jmsTemplate;

    @Value("${mes.activemq.brokerURL}")
    String brokerURL;

    @Pointcut("@annotation(com.foreverwin.jzymes.framework.annotation.MessageLog)")
    public void messageLog(){}

    @AfterReturning( pointcut = "messageLog()" )
    public void doAfterReturning( JoinPoint joinPoint ){
        handleLog( joinPoint, null );
    }

    @AfterThrowing( pointcut = "messageLog()", throwing = "e" )
    public void doAfterThrowing( JoinPoint joinPoint, Exception e ){
        handleLog( joinPoint, e );
    }

    public void handleLog( JoinPoint joinPoint, Exception e ){

        Object[] args = joinPoint.getArgs();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        JmsListener jmsListener = methodSignature.getMethod().getAnnotation( JmsListener.class );

        String queueName = jmsListener.destination();
        String messageBody = (String)args[0];

        //logger.info( "接收到信息: " + messageBody );

        JSONObject map = JSONObject.parseObject( messageBody );
        String site = map.getString( "SITE" );
        String ip = IPUtil.getIp();
        String result = null;
        String errorMsg = null;
        if( e == null ){
            result = "Y";
            //logger.info( "信息处理完成: " + messageBody );
        }else{
            result = "N";
            errorMsg = e.getMessage();
            //logger.info( "信息处理失败: " + errorMsg + ",信息：" + messageBody );
        }

        EapLog eapLog = new EapLog();
        eapLog.setHandle(UUID.randomUUID().toString() );
        eapLog.setSite( site );
        eapLog.setBrokeUrl( brokerURL );
        eapLog.setQueueName( queueName );
        eapLog.setMessageBody( messageBody != null && messageBody.length() > 2000 ? messageBody.substring( 0, 2000 ) : messageBody );
        eapLog.setResult( result );
        eapLog.setErrorMsg( errorMsg != null && errorMsg.length() > 2000 ? errorMsg.substring( 0, 2000 ) : errorMsg );
        eapLog.setServerIp( ip );
        eapLog.setCreatedDateTime( new Date() );

        jmsTemplate.convertAndSend( "MES_EAP_LOG", ObjectMapperUtil.writeValueAsString( eapLog ) );
    }
}
